package io.github.gaisad.amweb2.listener;

import day240904.MyDBUtil;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;

import java.sql.SQLException;

@WebListener
public class MyApplicationListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        int perPageCount = 6;
        String initPerPageCount = sce.getServletContext().getInitParameter("init_per_page_count");
        if (initPerPageCount != null) {
            perPageCount = Integer.parseInt(initPerPageCount);
            System.out.println("从 web.xml 的 context-param 中获取 init_per_page_count = " + perPageCount);
        }
        sce.getServletContext().setAttribute("defaultPerPageCount", perPageCount);
        System.out.println("=== 设置分页的默认每页显示条数 defaultPerPageCount=" + perPageCount);
        System.out.println("MyApplicationListener.contextInitialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            MyDBUtil.getConnection().close();
            System.out.println("Database connection closed");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("MyApplicationListener.contextDestroyed");
    }
}